package ch8;

/**
 * 控制线程的暂挂(suspend)与恢复(resume)的工具类
 * Thread.suspend()和Thread.resume()是两个已经被废弃的方法
 * 本demo中，使用一个线程暂挂标志和Condition来实现线程的暂挂与恢复
 * 基于Condition的await()和signalAll()来操作
 */

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class PauseControl extends ReentrantLock {
    private static final long serialVersionUID = 176912639934052187L;

    // 线程暂挂标志
    private volatile boolean suspended = false;
    private final Condition condSuspended = newCondition();

    /**
     * 暂停线程
     * 设置暂挂标志为true
     */
    public void requestPause() {
        suspended = true;
    }


    /**
     * 恢复线程
     * 设置暂挂标志为false，并唤醒线程
     */
    public void proceed() {
        lock();
        try {
            suspended = false;
            condSuspended.signalAll();
        } finally {
            unlock();
        }
    }

    /**
     * 当前线程仅在线程暂挂标记不为true的情况下才执行指定的目标动作
     */
    public void pauseIfNecessary(Runnable targetAction) throws InterruptedException {
        lock();
        try {
            while (suspended) {
                condSuspended.await();
            }
            targetAction.run();
        } finally {
            unlock();
        }
    }
}
